<script setup>
import { ref } from 'vue';
import { message } from 'ant-design-vue';
import axios from 'axios';

// 表单数据
const formData = ref({
  name: '',
  idCard: '',
  agreement: false
});

// 存储文件和预览 URL
const files = ref([]);
const fileUrls = ref([]);

// 处理文件上传
const handleImageUpload = (event) => {
  const uploadFiles = event.target.files;

  if (uploadFiles.length + files.value.length > 2) {
    message.error('最多只能上传2张图片');
    return;
  }

  for (const file of Array.from(uploadFiles)) {
    if (!['image/jpeg', 'image/png', 'image/gif'].includes(file.type)) {
      message.error('只支持 jpg、png、gif 格式的图片');
      continue;
    }
    if (file.size > 10 * 1024 * 1024) {
      message.error('图片大小不能超过10M');
      continue;
    }

    files.value.push(file);
    fileUrls.value.push(URL.createObjectURL(file));
  }
};

// 删除文件
const removeFile = (index) => {
  URL.revokeObjectURL(fileUrls.value[index]);
  files.value.splice(index, 1);
  fileUrls.value.splice(index, 1);
};

// 提交表单
const submitForm = async () => {
  if (!formData.value.agreement) {
    message.error('请同意协议');
    return;
  }

  const form = new FormData();
  form.append('name', formData.value.name);
  form.append('idCard', formData.value.idCard);
  files.value.forEach((file, index) => {
    form.append('files', file); // 确保字段名称为 files
  });

  try {
    const response = await axios.post('/api/upload', form);
    message.success('上传成功！');
    console.log('服务器响应:', response.data);
  } catch (error) {
    console.error('上传失败:', error);
    message.error('上传失败，请重试！');
  }
};
</script>

<template>
  <div>
    <form @submit.prevent="submitForm">
      <label>
        姓名:
        <input v-model="formData.name" type="text" required />
      </label>
      <label>
        身份证号:
        <input v-model="formData.idCard" type="text" required />
      </label>
      <label>
        上传图片:
        <input type="file" @change="handleImageUpload" multiple accept="image/*" />
      </label>
      <div>
        <div v-for="(url, index) in fileUrls" :key="index">
          <img :src="url" alt="预览" style="width: 100px; height: 100px;" />
          <button type="button" @click="removeFile(index)">删除</button>
        </div>
      </div>
      <label>
        <input v-model="formData.agreement" type="checkbox" /> 同意协议
      </label>
      <button type="submit">提交</button>
    </form>
  </div>
</template>
